<template>
    <div>
        <van-nav-bar
            title="我的订单"
            left-text="返回"
            left-arrow
            @click-left="onClickLeft"
        />
        <van-card
            v-for="item in orders"
            :desc="item.position"
            :price="item.product.price"
            :title="item.product.title"
            :thumb="
                'http://localhost:3000/' + item.product.product_images[0].url
            "
        >
            <template #tags v-if="item.product.product_labels.length">
                <van-tag
                    style="margin: 0 4px"
                    v-for="label in item.product.product_labels"
                    plain
                    type="primary"
                    >{{ label.name }}</van-tag
                >
            </template>
            <template #footer>
                <van-button
                    :type="
                        item.status == 0
                            ? 'warning'
                            : item.status == 1
                            ? 'danger'
                            : 'success'
                    "
                    size="small"
                    @click="handleOrder(item)"
                >
                    {{
                        item.status == 0
                            ? "等待发货"
                            : item.status == 1
                            ? "确认收货"
                            : "订单完成"
                    }}
                </van-button>
            </template>
        </van-card>
    </div>
</template>

<script setup>
import { useStore } from "vuex";
import { computed, onMounted, ref } from "vue";
import { useRouter } from "vue-router";

import { getOrder, updateOrder } from "@/api/basic";
import { Toast, Dialog, showToast } from "vant";
const VanDialog = Dialog.Component; //!!!!

const store = useStore();
const router = useRouter();
const orders = ref();

const userInfo = computed(() => {
    return store.getters.userInfo;
});

onMounted(() => {
    getOrderList();
});

const getOrderList = async () => {
    const { code, message, result } = await getOrder({
        userId: userInfo.value.id,
    });
    if (code != 200) {
        showToast(message);
        return;
    }
    orders.value = result.filter((ele) => ele.product);
};

const handleOrder = async (item) => {
    if (item.status == 0) {
        showToast("等待发货");
        return;
    }
    if (item.status == 1) {
        const { code, message, result } = await updateOrder({
            id: item.id,
            status: 2,
        });
        showToast(message);
        getOrderList();
    }
};

const onClickLeft = () => {
    router.back();
};
</script>
